package com.nosite.batch.server.quartz;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.configuration.JobLocator;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: SunYuGuo
 * @Date: 2019/11/17 21:41
 * @Description:
 */
@Component
@Slf4j
public class QuartzJobLauncher extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        JobDetail jobDetail = context.getJobDetail();
        JobDataMap jobDataMap = jobDetail.getJobDataMap();
        String jobName = jobDataMap.getString("jobName");
        JobLauncher jobLauncher = (JobLauncher) jobDataMap.get("jobLauncher");
        JobLocator jobLocator = (JobLocator) jobDataMap.get("jobLocator");
        log.info("jobName:{},jobLauncher:{},jobLocator:{}",jobName,jobLauncher,jobLocator);
        JobKey key = context.getJobDetail().getKey();
        log.info("JobKey:{}",key);
        try {
            Job job = jobLocator.getJob(jobName);
            /*启动spring batch的job*/
            Map<String, JobParameter> parameter = new HashMap<String,JobParameter>();
            parameter.put("date",new JobParameter(new Date()));
            JobExecution jobExecution = jobLauncher.run(job,new JobParameters(parameter));
        } catch (Exception e) {
            log.error("任务启动发生异常",e);
        }

    }
}
